#!/usr/bin/env node

const http = require('http'),
      fs   = require('fs'),
      qs   = require('querystring');

/*
function genPage(){
  let html = `<!DOCTYPE html>
      <html lang="en">
      <head>
        <meta charset="UTF-8">
        <title>todo list</title>
      </head>
      <body>
        <h1>Todo List</h1>
        <form action="http://192.168.178.144:8080" method="POST">
          <input type="text" name="item">
          <input type="submit" value="提交">
        </form>
        <ul id="items">
          ${items.map( i => '<li>' + i + '</li>').join('\n')}
        </ul>
    </body>
    </html>`;
  return html;
}
*/

http.createServer((req,res)=>{
  if(req.url !== '/'){
    res.statusCode = 404;
    res.setHeader('Content-Type','text/html');
    res.end('<h1>not found</h1>');
  }else{

    let data = '';
    req.setEncoding('binary');
    req.on('data',chunck => data += chunck); 
    
    req.on('end',()=>{
      
      data = data.split('\r\n');

      let filename = data[1].split('; ')[2].split('=')[1];
      filename = filename.slice(1,filename.length-1);
      data = data[4];
      fs.writeFileSync(filename,data,'binary');
      res.end('ok!');


    });

  }

}).listen(8080);
